// 解析wrk输出结果为JSON格式

const fs = require('fs');
const readline = require('readline');

const inputFile = './results/wrk-output.txt';
const outputFile = './results/report.json';

// 读取文件并解析
const parseResults = async () => {
  const fileStream = fs.createReadStream(inputFile);
  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity
  });

  const result = {
    timestamp: new Date().toISOString(),
    summary: {},
    latency: {},
    requests: {}
  };

  for await (const line of rl) {
    // 解析请求相关数据
    if (line.includes('Requests:')) {
      result.summary.requests = parseInt(line.split(':')[1].trim());
    }
    
    if (line.includes('Duration:')) {
      const duration = line.split(':')[1].trim();
      result.summary.duration = duration;
    }
    
    if (line.includes('Requests/sec:')) {
      result.requests.rate = parseFloat(line.split(':')[1].trim());
    }
  }

  // 写入JSON文件
  fs.writeFileSync(outputFile, JSON.stringify(result, null, 2));
  console.log('Results parsed and saved to', outputFile);
};

parseResults().catch(console.error);